package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 监听订单超时消息
 */
@Component
@Slf4j
public class OrderTimeoutListener {

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "order_dead_queue")
    public void orderTimeout(Channel channel, Message message){
        //1 获取到消息
        String orderIdStr = new String(message.getBody());
        Long orderId = Long.valueOf(orderIdStr);

        //获取消息对象属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try{
            //2 调用业务层的方法
            orderService.cancel(orderId);

            //3 确认收到消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            log.error("消息确认失败，原因为：" + e.getMessage());
            try{
                //4 异常处理
                if(messageProperties.getRedelivered()){
                    //消息确认两次都失败，丢弃
                    log.error("连续两次超时取消订单都失败,订单号为:" + orderId);
                    channel.basicReject(deliveryTag,false);
                }else{
                    //第一次确认消息出现异常，在来一次
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e2){
                log.error("拒绝消息发生异常,取消超时订单可能失败了,需要确认,订单号为:" + orderId);
            }
        }
    }
}
